package com.fable.biz.operate.impl;

import com.fable.base.PaginationResult;
import com.fable.biz.operate.WorkDailyService;
import com.fable.biz.operate.query.WorkDailyQueryCondition;
import com.fable.dal.mapper.ext.WorkDailyExtMapper;
import com.fable.dal.model.WorkDailyDO;
import com.fable.dal.model.WorkDailyQuery;
import com.fable.utils.CalendarUtil;
import com.fable.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by weishuai on 18/5/26.
 */
@Service("workDailyService")
public class WorkDailyServiceImpl implements WorkDailyService {

    @Autowired
    WorkDailyExtMapper workDailyExtMapper;

    @Override
    public int add(WorkDailyDO workDailyDO) {

        return workDailyExtMapper.insertSelective(workDailyDO);
    }

    @Override
    public void update(WorkDailyDO workDailyDO) {
        workDailyExtMapper.updateByPrimaryKeySelective(workDailyDO);
    }

    @Override
    public WorkDailyDO getById(Long id) {
        return workDailyExtMapper.selectByPrimaryKey(id);
    }

    @Override
    public PaginationResult<WorkDailyDO> searchWorkDaily(WorkDailyQueryCondition condition) {
        PaginationResult<WorkDailyDO> result = new PaginationResult<>();
        if (condition == null) {
            return result;
        }
        List<WorkDailyDO> list = new ArrayList<>();
        WorkDailyQuery query = new WorkDailyQuery();
        WorkDailyQuery.Criteria criteria = query.createCriteria();
        if (StringUtil.isNotBlank(condition.getUserName())) {
            criteria.andUserNameLike("%" + condition.getUserName() + "%");
        }
        if(condition.getUserId()!=null){
            criteria.andUserIdEqualTo(condition.getUserId());
        }

        if (StringUtil.isNotBlank(condition.getStartTime())) {
            criteria.andDateGreaterThanOrEqualTo(condition.getStartTime());
        }
        if (StringUtil.isNotBlank(condition.getEndTime())) {
            criteria.andDateLessThanOrEqualTo(condition.getEndTime());
        }
        if(StringUtil.isNotBlank(condition.getDate())){
            criteria.andDateEqualTo(condition.getDate());
        }

        query.setPageIndex((condition.getCurrent_page() - 1) * condition.getPageSize());
        query.setPageSize(condition.getPageSize());
        int count = workDailyExtMapper.countByquery(query);
        result.setPageSize(query.getPageSize());
        result.setTotalCount(count);
        result.setCurrentPage(condition.getCurrent_page());

        if (count > 0) {
            query.setOrderByClause("gmt_create desc");
            list = workDailyExtMapper.selectByquery(query);
            result.setResultList(list);
        }
        if (CollectionUtils.isEmpty(list)) {
            return result;
        }
        return result;
    }
}
